#!/usr/local/bin/python3
# -*- coding: utf-8 -*-

"""
@File    : chart_data_log.py
@Author  : Link
@Time    : 2023/6/11 20:43
@Mark    : 
"""

import win32api

import pandas as pd
from PySide2.QtCore import Slot
from PySide2.QtGui import QCloseEvent
from PySide2.QtWidgets import QFileDialog

from app_test.test_utils.wrapper_utils import Time
from chart_core.chart_pyqtgraph.ui_components.ui_unit_chart import UnitChartWindow
from common.app_variable import GlobalVariable
from common.data_class_interface.for_analysis_stdf import STDF_HEAD, PRR_HEAD
from common.li import FutureLi as Li
from ui_component.ui_app_variable import UiGlobalVariable
from ui_component.ui_common.my_text_browser import MQTextBrowser, UiMessage, Print


class DataLogChart(UnitChartWindow):
    """
    不需要Chart
    默认条件下只显示1000Row数据
    """
    log_df: pd.DataFrame = None

    def __init__(self, li: Li):
        super(DataLogChart, self).__init__()
        self.browser = MQTextBrowser(self)
        # self.browser.setStyleSheet("background-color: #DDDDDD;")
        self.setCentralWidget(self.browser)
        self.select_bin_dialog_button.setToolTip("将DataLog保存为CSV文件")
        if li is None:
            return
        self.li = li
        self.li.QChartSelect.connect(self.li_chart_signal)
        self.li.QChartRefresh.connect(self.li_chart_signal)

    def li_chart_signal(self):
        if self.action_signal_binding.isChecked():
            self.set_front_chart()

    # @Time()
    def set_front_chart(self):
        self.browser.clear()
        self.browser.m_append(UiMessage.Error("默认显示Logger行数: {}行!".format(UiGlobalVariable.PandasLogDefaultRow)))
        if self.li.df_module.log_df.empty:
            Print.Warning("STDF数据中没有DataTextRecord")
            return
        # 显示一些前置的Logger
        for log in self.li.df_module.log_df[self.li.df_module.log_df[PRR_HEAD.PART_ID] == 0].itertuples():
            logger: str = log.LOGGER
            self.browser.append(logger)
        if self.li.to_chart_csv_data.chart_df is None:
            df = self.li.to_chart_csv_data.df
        else:
            df = self.li.to_chart_csv_data.chart_df
        df = pd.merge(df, self.li.df_module.log_df, on=["ID", "PART_ID"])
        df = df[GlobalVariable.LOGGER_TXT_HEAD].copy()
        all_group_column = df[STDF_HEAD.GROUP] + "@" + df[PRR_HEAD.DA_GROUP]
        df.insert(0, column=STDF_HEAD.ALL_GROUP, value=all_group_column)
        # df.sort_values(by=PRR_HEAD.PART_ID, inplace=True)
        self.log_df = df
        show_log_df = df.head(UiGlobalVariable.PandasLogDefaultRow)
        end = ""
        for (group_text, part_id), df in show_log_df.groupby([STDF_HEAD.ALL_GROUP, PRR_HEAD.PART_ID]):
            self.browser.m_append(UiMessage.Warning("=" * 8 + str(group_text) + "=" * 8))
            for index, log in enumerate(df.itertuples()):
                if index == 0:
                    string = "PART_ID:{} X_COORD:{}, Y_COORD:{}, HARD_BIN:{}, SOFT_BIN:{}, FAIL_FLAG:{}".format(
                        part_id, log.X_COORD, log.Y_COORD, log.HARD_BIN, log.SOFT_BIN, log.FAIL_FLAG
                    )
                    if log.FAIL_FLAG:
                        self.browser.m_append(UiMessage.Success(string))
                    else:
                        self.browser.m_append(UiMessage.Error(string))
                    self.browser.insertPlainText("\n")
                    if '\n' not in log.LOGGER:
                        end = '\n'
                logger: str = log.LOGGER
                self.browser.insertPlainText(logger + end)

    @Slot()
    def _select_bin_dialog_button(self):
        """
        将数据保存为csv
        """
        if self.log_df is None:
            Print.Debug("未选取数据!")
            return
        save_file, suffix = QFileDialog.getSaveFileName(None,
                                                        caption='保存文件',
                                                        dir=GlobalVariable.SWAP_PATH,
                                                        filter='csv(*.csv)')
        if suffix not in {'csv(*.csv)', 'excel(*.xlsm)'}:
            self.statusbar.showMessage('取消数据保存')
            return
        if suffix != 'csv(*.csv)':
            return
        if self.log_df.empty:
            Print.Error("LogDf中无任何数据, 无法保存!")
            return
        self.log_df.to_csv(save_file, encoding='utf_8_sig', index=False)
        Print.Debug("LogDf数据保存成功, 打开中!")
        win32api.ShellExecute(0, 'open', save_file, '', '', 1)
